<template>
  <div class="hosts-container">
    <el-row :gutter="20" style="margin-bottom: 24px;">
      <el-col :span="6">
        <div class="stat-card">
          <el-icon :size="40" color="#3a84ff"><Monitor /></el-icon>
          <div class="stat-value">{{ stats.total }}</div>
          <div class="stat-label">总主机数</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <el-icon :size="40" color="#67c23a"><CircleCheck /></el-icon>
          <div class="stat-value" style="color: #67c23a;">{{ stats.online }}</div>
          <div class="stat-label">在线</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <el-icon :size="40" color="#f56c6c"><CircleClose /></el-icon>
          <div class="stat-value" style="color: #f56c6c;">{{ stats.offline }}</div>
          <div class="stat-label">离线</div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <el-icon :size="40" color="#e6a23c"><Warning /></el-icon>
          <div class="stat-value" style="color: #e6a23c;">{{ stats.maintenance }}</div>
          <div class="stat-label">维护中</div>
        </div>
      </el-col>
    </el-row>

    <div class="dashboard-card" style="padding: 20px;">
      <div class="card-header">
        <div class="header-actions">
          <el-input 
            v-model="searchText" 
            placeholder="搜索IP/主机名/操作系统" 
            style="width: 250px; margin-right: 10px;"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select v-model="refreshInterval" placeholder="刷新间隔" style="width: 130px; margin-right: 10px;" @change="changeRefreshInterval">
            <el-option label="不自动刷新" :value="0" />
            <el-option label="10秒" :value="10" />
            <el-option label="30秒" :value="30" />
            <el-option label="60秒" :value="60" />
            <el-option label="5分钟" :value="300" />
          </el-select>
          
          <el-button @click="refreshMonitorData" :loading="refreshing">
            <el-icon><Refresh /></el-icon> 刷新
          </el-button>
          
          <el-button type="warning" @click="checkAllStatus" :loading="checkingStatus">
            <el-icon><Connection /></el-icon> {{ checkingStatus ? '检测中...' : '检测状态' }}
          </el-button>
          
          <el-button type="success" @click="exportHosts">
            <el-icon><Download /></el-icon> 导出
          </el-button>
          
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImport"
            accept=".xlsx,.xls"
            style="display: inline-block; margin: 0 10px;"
          >
            <el-button type="warning">
              <el-icon><Upload /></el-icon> 导入
            </el-button>
          </el-upload>
          
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon> 添加
          </el-button>
        </div>
      </div>

      <el-table :data="filteredHosts" style="width: 100%; margin-top: 20px;" :default-sort="{prop: 'ip', order: 'ascending'}">
        <el-table-column prop="ip" label="IP地址" width="130" sortable />
        <el-table-column prop="port" label="端口" width="70" />
        <el-table-column prop="username" label="用户名" width="90" />
        <el-table-column label="服务器类型" width="120">
          <template #default="{ row }">
            <el-tag type="info" size="small">{{ row.server_type_display || '其他' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="主机组" width="110">
          <template #default="{ row }">
            <span v-if="row.host_group_name">{{ row.host_group_name }}</span>
            <span v-else style="color: #909399;">未分组</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'online'" type="success" size="small">在线</el-tag>
            <el-tag v-else-if="row.status === 'offline'" type="danger" size="small">离线</el-tag>
            <el-tag v-else type="warning" size="small">维护中</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="CPU" width="140">
          <template #default="{ row }">
            <div v-if="row.monitorData" class="monitor-cell">
              <el-progress :percentage="Math.round(row.monitorData.cpu_usage)" :color="getProgressColor(row.monitorData.cpu_usage)" :stroke-width="6" :show-text="true" />
            </div>
            <span v-else class="loading-text">-</span>
          </template>
        </el-table-column>
        <el-table-column label="内存" width="180">
          <template #default="{ row }">
            <div v-if="row.monitorData" class="monitor-cell">
              <el-progress :percentage="Math.round(row.monitorData.mem_usage)" :color="getProgressColor(row.monitorData.mem_usage)" :stroke-width="6" :show-text="false" />
              <div class="monitor-text">
                {{ Math.round(row.monitorData.mem_usage) }}% ({{ row.monitorData.mem_used }}MB/{{ row.monitorData.mem_total }}MB)
              </div>
            </div>
            <span v-else class="loading-text">-</span>
          </template>
        </el-table-column>
        <el-table-column label="磁盘" width="180">
          <template #default="{ row }">
            <div v-if="row.monitorData" class="monitor-cell">
              <el-progress :percentage="Math.round(row.monitorData.disk_usage)" :color="getProgressColor(row.monitorData.disk_usage)" :stroke-width="6" :show-text="false" />
              <div class="monitor-text" v-if="row.monitorData.disk_used && row.monitorData.disk_total">
                {{ Math.round(row.monitorData.disk_usage) }}% ({{ row.monitorData.disk_used }}/{{ row.monitorData.disk_total }})
              </div>
              <div class="monitor-text" v-else>
                {{ Math.round(row.monitorData.disk_usage) }}%
              </div>
            </div>
            <span v-else class="loading-text">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作系统" width="250" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.monitorData">{{ row.monitorData.os_version || row.os_version || '-' }}</span>
            <span v-else>{{ row.os_version || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="openTerminal(row)">
              <el-icon><Monitor /></el-icon> 终端
            </el-button>
            <el-button size="small" type="warning" @click="checkSingleStatus(row)" :loading="row.checking">
              检测
            </el-button>
            <el-button size="small" type="primary" @click="editHost(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteHost(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑主机' : '添加主机'" width="600px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="主机名">
          <el-input v-model="form.hostname" placeholder="请输入主机名" />
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input v-model="form.ip" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="SSH端口">
          <el-input v-model.number="form.port" placeholder="默认22" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="默认root" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" placeholder="SSH密码" />
        </el-form-item>
        <el-form-item label="服务器类型">
          <el-select v-model="form.server_type" placeholder="请选择服务器类型" style="width: 100%;">
            <el-option label="数据库服务器" value="database" />
            <el-option label="Web服务器" value="web" />
            <el-option label="Ansible服务器" value="ansible" />
            <el-option label="缓存服务器" value="cache" />
            <el-option label="消息队列服务器" value="mq" />
            <el-option label="存储服务器" value="storage" />
            <el-option label="监控服务器" value="monitor" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="主机组">
          <el-select v-model="form.host_group" placeholder="请选择主机组（可选）" style="width: 100%;" clearable>
            <el-option 
              v-for="group in hostGroups" 
              :key="group.id" 
              :label="group.name" 
              :value="group.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" style="width: 100%;">
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
            <el-option label="维护中" value="maintenance" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作系统">
          <el-input v-model="form.os_version" placeholder="如: Ubuntu 20.04" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { hostAPI, hostGroupAPI } from '@/api'

const router = useRouter()
const stats = ref({ total: 0, online: 0, offline: 0, maintenance: 0 })
const hosts = ref([])
const hostGroups = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = ref({
  hostname: '', ip: '', port: 22, username: 'root', password: '',
  status: 'online', server_type: 'other', host_group: null, os_version: ''
})
let monitorTimer = null
const searchText = ref('')
const refreshInterval = ref(30)
const refreshing = ref(false)
const uploadRef = ref(null)
const checkingStatus = ref(false)

const fetchStats = async () => {
  try {
    stats.value = await hostAPI.stats()
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

const fetchHosts = async () => {
  try {
    const data = await hostAPI.list()
    hosts.value = data.results || data
    // 获取每个主机的监控数据
    fetchAllMonitorData()
  } catch (error) {
    ElMessage.error('获取主机列表失败')
  }
}

const fetchHostGroups = async () => {
  try {
    const data = await hostGroupAPI.list()
    hostGroups.value = data.results || data
  } catch (error) {
    console.error('获取主机组列表失败:', error)
  }
}

const fetchAllMonitorData = async () => {
  for (const host of hosts.value) {
    if (host.status === 'online') {
      try {
        const monitorData = await hostAPI.monitor(host.id)
        host.monitorData = monitorData
      } catch (error) {
        console.error(`获取主机 ${host.ip} 监控数据失败:`, error)
        host.monitorData = {
          cpu_usage: 0,
          mem_usage: 0,
          disk_usage: 0,
          os_version: host.os_version || 'Unknown'
        }
      }
    }
  }
}

const filteredHosts = computed(() => {
  if (!searchText.value) {
    return hosts.value
  }
  const search = searchText.value.toLowerCase()
  return hosts.value.filter(host => {
    return host.ip.toLowerCase().includes(search) ||
           (host.hostname && host.hostname.toLowerCase().includes(search)) ||
           (host.os_version && host.os_version.toLowerCase().includes(search)) ||
           (host.monitorData && host.monitorData.os_version && host.monitorData.os_version.toLowerCase().includes(search))
  })
})

const refreshMonitorData = async () => {
  refreshing.value = true
  try {
    await fetchAllMonitorData()
    ElMessage.success('刷新成功')
  } catch (error) {
    ElMessage.error('刷新失败')
  } finally {
    refreshing.value = false
  }
}

const changeRefreshInterval = (value) => {
  if (monitorTimer) {
    clearInterval(monitorTimer)
    monitorTimer = null
  }
  
  if (value > 0) {
    monitorTimer = setInterval(() => {
      fetchAllMonitorData()
    }, value * 1000)
    ElMessage.success(`已设置为每${value < 60 ? value + '秒' : (value / 60) + '分钟'}自动刷新`)
  } else {
    ElMessage.info('已关闭自动刷新')
  }
}

const exportHosts = async () => {
  try {
    const response = await hostAPI.export()
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `主机列表_${new Date().getTime()}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

const handleImport = async (file) => {
  try {
    const result = await hostAPI.import(file.raw)
    if (result.success) {
      ElMessage.success(`导入完成！成功: ${result.success_count}, 失败: ${result.error_count}`)
      if (result.errors && result.errors.length > 0) {
        console.error('导入错误:', result.errors)
      }
      fetchHosts()
      fetchStats()
    }
  } catch (error) {
    ElMessage.error('导入失败')
  }
}

const getProgressColor = (percentage) => {
  if (percentage < 60) {
    return '#67c23a' // 绿色
  } else if (percentage < 80) {
    return '#e6a23c' // 橙色
  } else {
    return '#f56c6c' // 红色
  }
}

const showAddDialog = () => {
  isEdit.value = false
  form.value = { 
    hostname: '', ip: '', port: 22, username: 'root', password: '', 
    status: 'online', server_type: 'other', host_group: null, os_version: '' 
  }
  dialogVisible.value = true
}

const editHost = (host) => {
  isEdit.value = true
  form.value = { ...host }
  dialogVisible.value = true
}

const submitForm = async () => {
  try {
    if (isEdit.value) {
      await hostAPI.update(form.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await hostAPI.create(form.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    fetchHosts()
    fetchStats()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const deleteHost = (host) => {
  ElMessageBox.confirm('确定要删除该主机吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await hostAPI.delete(host.id)
      ElMessage.success('删除成功')
      fetchHosts()
      fetchStats()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const openTerminal = (host) => {
  router.push(`/terminal/${host.id}`)
}

// 检测单个主机状态
const checkSingleStatus = async (host) => {
  host.checking = true
  try {
    const result = await hostAPI.checkStatus(host.id)
    host.status = result.status
    ElMessage.success(result.message)
    fetchStats()
  } catch (error) {
    ElMessage.error('检测失败')
  } finally {
    host.checking = false
  }
}

// 检测所有主机状态
const checkAllStatus = async () => {
  checkingStatus.value = true
  try {
    const result = await hostAPI.checkAllStatus()
    ElMessage.success(`检测完成：在线 ${result.online} 台，离线 ${result.offline} 台`)
    fetchHosts()
    fetchStats()
  } catch (error) {
    ElMessage.error('批量检测失败')
  } finally {
    checkingStatus.value = false
  }
}

onMounted(() => {
  fetchStats()
  fetchHosts()
  fetchHostGroups()
  // 默认30秒刷新一次监控数据
  changeRefreshInterval(refreshInterval.value)
})

onUnmounted(() => {
  if (monitorTimer) {
    clearInterval(monitorTimer)
  }
})
</script>

<style scoped>
.hosts-container {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 10px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.card-header h3 {
  margin: 0;
  color: #3a84ff;
  font-size: 20px;
}

.monitor-cell {
  padding: 5px 0;
}

.monitor-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 11px;
  margin-top: 4px;
  text-align: center;
}

.loading-text {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
}

:deep(.el-progress__text) {
  color: #fff !important;
  font-size: 11px !important;
  min-width: 38px !important;
}

:deep(.el-table .cell) {
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: nowrap !important;
  padding-left: 10px !important;
  padding-right: 10px !important;
}

:deep(.el-table) {
  overflow-x: auto !important;
}

:deep(.el-table__body-wrapper) {
  overflow-x: auto !important;
}
</style>
